<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="仓库编码" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入仓库编码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="仓库名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入仓库名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="仓库状态" prop="status" style="width: 250px">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择仓库状态"
          clearable
        >
          <el-option
            v-for="dict in status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['basics:warehouse:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['basics:warehouse:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['basics:warehouse:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['basics:warehouse:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="warehouseList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="id" />
      <el-table-column label="仓库编码" align="center" prop="code" />
      <el-table-column label="仓库名称" align="center" prop="name" />
      <el-table-column label="仓库类型" align="center" prop="type" />
      <el-table-column label="省/市/区" align="center" prop="location" />
      <el-table-column label="详细地址" align="center" prop="address" />
      <el-table-column label="仓库面积" align="center" prop="surface" />
      <el-table-column label="负责人姓名" align="center" prop="personName" />
      <el-table-column label="联系电话" align="center" prop="phone" />
      <el-table-column label="库区数量" align="center" prop="includedNum" />
      <el-table-column label="仓库状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column
        label="更新时间"
        align="center"
        prop="updateTime"
        width="180"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.updateTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['basics:warehouse:edit']"
            >修改</el-button
          >
          <el-button type="primary" link @click="handleToggleStatus(scope.row)">
            <span v-if="scope.row.status === 1">启用</span>
            <span v-if="scope.row.status === 0">停用</span>
          </el-button>
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['basics:warehouse:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改仓库管理对话框 -->
    <el-dialog :title="title" v-model="open" append-to-body>
      <el-form ref="warehouseRef" :model="form" :rules="rules">
        <el-form-item label="仓库编码">
          {{ form.code }}
        </el-form-item>
        <el-form-item label="仓库名称" prop="name">
          <el-input
            v-model="form.name"
            style="width: 500px"
            placeholder="请输入仓库名称"
          />
        </el-form-item>
        <el-form-item label="仓库类型" prop="type">
          <el-select
            v-model="form.type"
            style="width: 500px"
            placeholder="请选择仓库类型"
            clearable
          >
            <el-option
              v-for="dict in typeList"
              :key="dict.id"
              :label="dict.type"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="省/市/区">
          <el-select
            v-model="form.province"
            placeholder="请选择省"
            @change="loadCities"
            style="width: 100px"
          >
            <el-option
              v-for="province in provinces"
              :key="province.code"
              :label="province.name"
              :value="province.name"
            />
          </el-select>
          &emsp;
          <el-select
            v-model="form.city"
            placeholder="请选择市"
            @change="loadAreas"
            style="width: 100px"
          >
            <el-option
              v-for="city in cities"
              :key="city.code"
              :label="city.name"
              :value="city.name"
            />
          </el-select>
          &emsp;
          <el-select
            v-model="form.area"
            style="width: 100px"
            placeholder="请选择区"
          >
            <el-option
              v-for="area in areas"
              :key="area.code"
              :label="area.name"
              :value="area.name"
            />
          </el-select>
        </el-form-item> -->
        <el-form-item label="详细地址" prop="address">
          <el-input
            v-model="form.address"
            style="width: 500px"
            placeholder="请输入详细地址"
          />
        </el-form-item>
        <el-form-item label="仓库面积" prop="surface">
          <el-input
            v-model="form.surface"
            style="width: 450px"
            placeholder="请输入仓库面积"
          />
          &emsp; m²
        </el-form-item>
        <el-form-item label="负责人" prop="personName">
          <el-input
            v-model="form.personName"
            style="width: 500px"
            placeholder="请输入负责人姓名"
          />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input
            v-model="form.phone"
            style="width: 500px"
            placeholder="请输入联系电话"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Warehouse">
import {
  listWarehouse,
  getWarehouse,
  delWarehouse,
  addWarehouse,
  updateWarehouse,
  updateWarehouseStatus,
  generateWarehouseCode,
} from "@/api/basics/warehouse";
import { ElMessageBox, ElMessage } from "element-plus";

const { proxy } = getCurrentInstance();
const { status } = proxy.useDict("status");

// const provinces = ref(provincesData); // 省列表
// const cities = ref([]); // 市列表
// const areas = ref([]); // 区列表
const warehouseList = ref([]);
const typeList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    code: null,
    name: null,
    status: null,
    province: "",
    city: "",
    area: "",
  },
  rules: {
    name: [{ required: true, message: "仓库名称不能为空", trigger: "blur" }],
    type: [{ required: true, message: "仓库类型不能为空", trigger: "change" }],
    location: [
      { required: true, message: "省市区描述不能为空", trigger: "blur" },
    ],
    province: [{ required: true, message: "省不能为空", trigger: "blur" }],
    city: [{ required: true, message: "市不能为空", trigger: "blur" }],
    area: [{ required: true, message: "区不能为空", trigger: "blur" }],
    address: [{ required: true, message: "详细地址不能为空", trigger: "blur" }],
    surface: [{ required: true, message: "仓库面积不能为空", trigger: "blur" }],
    personName: [
      { required: true, message: "负责人姓名不能为空", trigger: "blur" },
    ],
    phone: [{ required: true, message: "联系电话不能为空", trigger: "blur" }],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询仓库管理列表 */
function getList() {
  loading.value = true;
  listWarehouse(queryParams.value).then((response) => {
    console.log(response);
    warehouseList.value = response.rows;
    typeList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    code: null,
    name: null,
    type: null,
    location: null,
    province: null,
    city: null,
    area: null,
    address: null,
    surface: null,
    personId: null,
    personName: null,
    phone: null,
    includedNum: null,
    status: null,
    remark: null,
    createUser: null,
    createName: null,
    createTime: null,
    updateUser: null,
    updateName: null,
    updateTime: null,
    logicDel: null,
  };
  proxy.resetForm("warehouseRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
async function handleAdd() {
  reset();
  try {
    const res = await generateWarehouseCode();
    console.log("生成编码结果:", res);
    form.value.code = res; // 将后端返回的编码赋值给表单
  } catch (error) {
    ElMessage.error("生成仓库编码失败");
  }
  open.value = true;
  title.value = "添加仓库管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getWarehouse(_id).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改仓库管理";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["warehouseRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updateWarehouse(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addWarehouse(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除仓库管理编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delWarehouse(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "basics/warehouse/export",
    {
      ...queryParams.value,
    },
    `warehouse_${new Date().getTime()}.xlsx`
  );
}

const handleToggleStatus = async (row) => {
  // 弹窗文案
  const status = row.status === 1 ? "启用" : "停用";
  const newStatus = row.status;
  try {
    // 1. 弹出确认弹窗（修正：需要await获取用户操作结果）
    await ElMessageBox.confirm(`确认${status}仓库${row.name}吗？`, "操作确认", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });
    // 2. 调用后端接口（修正：传递正确的参数）
    const res = await updateWarehouseStatus(row.id, newStatus);

    if (res.code === 200) {
      // 更新本地状态
      // row.status = newStatus;
      ElMessage.success(`${status}成功`);
      getList();
    } else {
      ElMessage.error(res.msg || "操作失败");
    }
  } catch (error) {
    // 取消操作
    if (error.name === "Cancel") {
      ElMessage.info("已取消操作");
    } else {
      console.error("状态更新失败:", error);
      ElMessage.error("操作失败，请重试");
    }
  }
};

// 模拟修改操作
const handleEdit = (row) => {
  ElMessage.info(`即将修改仓库${row.name}，可在这里写调用编辑弹窗或接口的逻辑`);
};

getList();
</script>
